package com.clas.liu.myapplication.view.activity.impl;

import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.presenter.impl.BasePresenter;
import com.clas.liu.myapplication.view.activity.i.IBaseActivity;
import com.clas.liu.myapplication.view.activity.impl.BaseActivity;
import com.clas.liu.myapplication.view.adapter.MainFragmentAdapter;
import com.clas.liu.myapplication.view.fragment.impl.ChatFragment;
import com.clas.liu.myapplication.view.fragment.impl.HomeFragment;
import com.clas.liu.myapplication.view.fragment.impl.SquareFragment;
import com.clas.liu.myapplication.view.fragment.impl.UserFragment;
import com.clas.liu.myapplication.view.util.PopupMenuUtil;
import com.clas.liu.myapplication.view.util.SaveUtil;
import com.clas.liu.myapplication.view.widget.MainTabButton;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.util.EMLog;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements IBaseActivity, View.OnClickListener {

    private ViewPager mFragmentPager;
    private int currentTabButton;
    private List<MainTabButton> tabButtons;
    private RelativeLayout add;
    private MainFragmentAdapter fragmentAdapter;
    private ArrayList<Fragment> fragments;
    private EMMessageListener messageListener;
    private long exitTime = 0;
    private int noticeCount;

    protected long lastNotifyTime;
    protected Ringtone ringtone = null;
    protected AudioManager audioManager;
    protected Vibrator vibrator;

    protected static final long[] VIBRATION_PATTERN = new long[]{0, 180, 80, 120};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setStatusBarTransparent();
        findView();
        init();
        setListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        updateUnreadLabel();
        showUnReadNoticeCount();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
    }

    private void setListener() {
        for (MainTabButton button : tabButtons) {
            button.setOnClickListener(this);
        }
        mFragmentPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.i("test", "onPageSelected: " + "滑到" + position);
                tabSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        add.setOnClickListener(this);
        messageListener = new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> list) {
                for (EMMessage message : list) {
                    vibrateAndPlayTone(message);
                    message.setMsgTime(System.currentTimeMillis());
                    //************接收并处理扩展消息***********************
                    String userName = message.getStringAttribute("userName", "");
                    String userPic = message.getStringAttribute("userPic", "");
                    String hxIdFrom = message.getFrom();
                    EaseUser easeUser = new EaseUser(hxIdFrom);
                    easeUser.setAvatar(userPic);
                    easeUser.setNickname(userName);
                    SaveUtil.saveChatUser(MainActivity.this.getApplicationContext(),
                            String.valueOf(hxIdFrom),userName,userPic);

                }
                refreshUIWithMessage();

            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> list) {
                refreshUIWithMessage();
            }

            @Override
            public void onMessageRead(List<EMMessage> list) {
            }

            @Override
            public void onMessageDelivered(List<EMMessage> list) {

            }

            @Override
            public void onMessageRecalled(List<EMMessage> list) {
                refreshUIWithMessage();
            }

            @Override
            public void onMessageChanged(EMMessage emMessage, Object o) {

            }
        };
    }

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
                if (currentTabButton == 2) {
                    // refresh conversation list
                    if (fragments.get(currentTabButton) != null) {
                        (((ChatFragment) fragments.get(currentTabButton))).refresh();
                    }
                }
            }
        });
    }

    private void updateUnreadLabel() {
        int unReadCoutn = EMClient.getInstance().chatManager().getUnreadMessageCount();
        tabButtons.get(2).showCount(unReadCoutn);
    }

    /**
     * vibrate and  play tone
     */
    public void vibrateAndPlayTone(EMMessage message) {
        EaseUI.getInstance().getNotifier().vibrateAndPlayTone(message);
    }

    private void init() {
        tabButtons.get(0).setSelected(true, 0);
        currentTabButton = 0;
        fragments = new ArrayList<Fragment>();
        fragments.add(new HomeFragment());
        fragments.add(new SquareFragment());
        fragments.add(new ChatFragment());
        fragments.add(new UserFragment());
        fragmentAdapter = new MainFragmentAdapter(getSupportFragmentManager(), fragments);
        mFragmentPager.setAdapter(fragmentAdapter);
        if (EMClient.getInstance().chatManager().getUnreadMessageCount()!=0) {
            vibrateAndPlayTone(null
            );
        }
    }

    private void findView() {
        tabButtons = new ArrayList<MainTabButton>();
        tabButtons.add((MainTabButton) findViewById(R.id.main_tab_1));
        tabButtons.add((MainTabButton) findViewById(R.id.main_tab_2));
        tabButtons.add((MainTabButton) findViewById(R.id.main_tab_3));
        tabButtons.add((MainTabButton) findViewById(R.id.main_tab_4));

        add = findViewById(R.id.main_tab_add);
        mFragmentPager = findViewById(R.id.main_fragment_viewpager);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void failBecauseNetReturn(int code) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_tab_1:
                tabSelected(0);
                break;
            case R.id.main_tab_2:
                tabSelected(1);
                break;
            case R.id.main_tab_3:
                tabSelected(2);
                break;
            case R.id.main_tab_4:
                tabSelected(3);
                break;
            case R.id.main_tab_add:
                PopupMenuUtil.getInstance()._show(this, add);
                break;
        }
    }

    public void tabSelected(int position) {
        if (position != currentTabButton) {
            tabButtons.get(position).setSelected(true, position);
            tabButtons.get(currentTabButton).setSelected(false, currentTabButton);
            currentTabButton = position;
            mFragmentPager.setCurrentItem(position);
        }
    }

    @Override
    public void onBackPressed() {
        // 当popupWindow 正在展示的时候 按下返回键 关闭popupWindow 否则关闭activity
        if (PopupMenuUtil.getInstance()._isShowing()) {
            PopupMenuUtil.getInstance()._rlClickAction();
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("再按一次退出程序",
                        Toast.LENGTH_SHORT);
                exitTime = System.currentTimeMillis();
            } else {
                super.onBackPressed();
            }
        }
    }

    private void exit() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 102) {
            if (((UserFragment)fragments.get(3))!=null) {
                ((UserFragment)fragments.get(3)).updateUser();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void setNoticeCount(int count) {
        this.noticeCount = count;
        showUnReadNoticeCount();
    }

    private void showUnReadNoticeCount() {
        int cur_count = SaveUtil.getNoticeCount(getApplicationContext());
        if (cur_count<=noticeCount) {
            tabButtons.get(0).showCount(noticeCount-cur_count);
        }
    }
}
